using UnityEngine;
using JufGame.MathHelper;

namespace JufGame.CptMod
{
	/// <summary>
	/// 返回时间：玩家返回时记忆度的期望衰减因子以及玩家返回的概率
	/// </summary>
	public class ReturnTime
	{
		public float RTValue { get; private set; } = 0;
		private const float MAX_EPOW = 1E+8f;
		private readonly float k = 0.8f; //k取0.8的情况下，返回时间接近韦伯分布 
		private readonly EMA L_EMA;//注意程度总负载预测EMA
		private float t0 = 0.02f;
		public ReturnTime(float smoothLoad = 0.1f)
		{
			L_EMA = new EMA(smoothLoad);
		}
		/// <summary>
		/// 基于Weibull hazard函数计算返回时间
		/// </summary>
		/// <param name="totalAtnLoad">当前总注意程度负载</param>
		public void CalculateReturnTime(float totalAtnLoad, float lastObsTime, float deltaTime)
		{
			// t0 = 上次被看到的时间直到现在持续的时间
			t0 = Time.time - lastObsTime + deltaTime;
			//EMA预测未来总负载
			totalAtnLoad = L_EMA.CalculateEMA(totalAtnLoad, deltaTime);
			var Lt0 = totalAtnLoad * t0;
			//约束e^(L*t0)范围，避免t0过大而无限增大
			var ePowLt0 = Mathf.Min(MAX_EPOW, Mathf.Exp(Lt0));
			// 计算返回时间 Ri = k(L)^(-k) * e^(L*t0) * Γ(k, Lt0)
			RTValue = k * Mathf.Pow(totalAtnLoad, -k) * ePowLt0 * (float)SpecialFunctions.GammaUpperIncomplete(k, Lt0);
		}
	}
}
